package utd.cs6322.cluster;

import java.io.File;
import java.io.FileNotFoundException;

import prefuse.data.Graph;
import prefuse.data.Node;
import prefuse.data.io.DataIOException;

import net.sf.javaml.clustering.Clusterer;
import net.sf.javaml.clustering.FarthestFirst;
import net.sf.javaml.clustering.KMeans;
import net.sf.javaml.clustering.KMedoids;
import net.sf.javaml.distance.CosineSimilarity;
import net.sf.javaml.core.Dataset;

import utd.cs6322.cluster.document.DocumentManager;
import utd.cs6322.cluster.visualization.TreeBuilder;

public class DataClusterer {
	public static void main(String args[]) {

		DocumentManager docman = new DocumentManager();

		docman.readDocument(new File(args[0]));

		Dataset data = docman.getData();

		FarthestFirst ff;
		KMeans km;
		KMedoids kmd;

		km = new KMeans(7, 10, new CosineSimilarity());
		ff = new FarthestFirst(7, new CosineSimilarity());
		kmd = new KMedoids(7, 10, new CosineSimilarity());

		try {
			clusterGraphAndWrite(ff, data, new File("FarthestFirst"));
			clusterGraphAndWrite(kmd, data, new File("KMedoids"));
			clusterGraphAndWrite(km, data, new File("KMeans"));
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
		
	} 
	
	private static void clusterGraphAndWrite(Clusterer clust, Dataset data, File file) throws FileNotFoundException, DataIOException{
		TreeBuilder builder = new TreeBuilder();

		Node root = builder.setRootDocs(data);
		
		Dataset[] level1 = clust.cluster(data);
		
		Dataset[][] level2 = new Dataset[level1.length][];
		
		for(int i = 0; i < level1.length; i++){
			Node currParent = builder.addCluster(root, level1[i]);
			level2[i] = clust.cluster(level1[i]);
			for(int j = 0; j < level2[i].length; j++){
				builder.addCluster(currParent, level2[i][j]);
			}
		}
		
		builder.writeTree(file);
	}
}
